/*
** map.c for pud in mrcellophane/libpud
** 
** Made by solomon hykes
** Login   <torgau@gmail.com>
** 
** Started on  Tue May 17 20:08:38 2005 solomon hykes
** Last update Thu Jul 14 14:38:19 2005 solomon hykes
*/

#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include "pud.h"
#include <sys/mman.h>

static pud_process	*proc = NULL;

void	bye(int sig)
{
  if (proc != NULL)
    pud_detach(proc);
  printf("Terminated by signal %d\n", sig);
  exit(0);
}

int	main(int argc, char **argv)
{
  pud_map	*maps;
  pud_event	*event;
  pud_map	*m;

  if (argc < 2)
    {
      fputs("Usage: psmap pid", stderr);
      exit(1);
    }
  signal(SIGINT, bye);
  signal(SIGSEGV, bye);
  proc = pud_attach(atoi(argv[1]));
  if (proc == NULL)
    {
      perror("pud_attach");
      exit(1);
    }
  event = pud_next_event(proc);
  if (event == NULL)
    {
      perror("pud_next_event");
      exit(1);
    }
  for (m = pud_get_maps(proc); m != NULL; m = m->next)
    {
      char	name[128];
      int	fd;
      char	*data;
      int	ret;

      printf("[%p] [%d] [%c%c%c]\n",
	     m->start,
	     m->size,
	     (m->prot & PROT_READ) ? 'r' : '-',
	     (m->prot & PROT_WRITE) ? 'w' : '-',
	     (m->prot & PROT_EXEC) ? 'x' : '-'
	     );
/*       if (!(m->prot & PROT_READ)) */
/* 	{ */
/* 	  printf(" Read-protected: skipping\n"); */
/* 	  continue; */
/* 	} */
/*       else */
/* 	printf("\n"); */
/*       sprintf(name, "%d.%p", proc->pid, m->start); */
/*       if ((fd = open(name, O_WRONLY|O_CREAT, 0600)) == -1) */
/* 	{ */
/* 	  perror(name); */
/* 	  exit(1); */
/* 	} */
/*       data = malloc(m->size); */
/*       if ((ret = pud_mem_read(proc, m->start, data, m->size)) == -1) */
/* 	{ */
/* 	  perror("pud_mem_read"); */
/* 	  exit(1); */
/* 	} */
/*       write(fd, data, ret); */
/*       close(fd); */
/*       free(data); */
    }
  pud_detach(proc);
}
